import cv2
from utils.cross_line import intersection_rect_poly
import numpy as np
from collections import deque

# from utils.assert_fuc import assert_function
"""
判断多边形和矩形是否相交
1 先判断他们的控制矩形是否相交。[多边形的控制矩形，即能围住多边形的最小矩形。]
2 判断点是否在多边形中。
"""


def draw_box(box_info, img, camera_ip, pp, personNum, polypoint):
    for i in range(len(polypoint)):
        cv2.line(img, tuple(polypoint[i-1]), tuple(polypoint[i]), (0, 0, 255), 2)
    y_len, x_len = img.shape[:2]
    crowed_num = 0  # 与多边形相交的矩形个数，即聚集人群数
    for box, score, label in box_info:
        '''draw rectangles'''
        if label == 'person' or label == 'car':
            y_min, x_min, y_max, x_max = box
            y_min, x_min, y_max, x_max = int(y_min * y_len), int(x_min * x_len), int(y_max * y_len), int(x_max * x_len)
            if intersection_rect_poly(polypoint, (x_max, x_min), (y_max, y_min)):
                crowed_num += 1
                if crowed_num >= personNum:
                    cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (0, 0, 255), thickness=3)
                else:
                    cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (0, 255, 0), thickness=3)
            else:
                cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (0, 255, 0), thickness=3)
    pp.p.stdin.write(img.tostring())

"""
# 先画框，再进行检测
def calculate_box(box_info, img, camera_ip, persons):
    for i in range(len(self.tpPointsChoose)):
        cv2.line(img, tuple(self.tpPointsChoose[i-1]), tuple(self.tpPointsChoose[i]), (0, 0, 255), 2)
    y_len, x_len = img.shape[:2]
    crowed_num = 0  # 与多边形相交的矩形个数，即在岗人数
    for box, score, label in box_info:
        '''draw rectangles'''
        if label == 'person' or label == 'car':
            y_min, x_min, y_max, x_max = box
            y_min, x_min, y_max, x_max = int(y_min * y_len), int(x_min * x_len), int(y_max * y_len), int(x_max * x_len)

            if intersection_rect_poly(self.tpPointsChoose, (x_max, x_min), (y_max, y_min)):
                crowed_num += 1
                cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (0, 255, 0), thickness=3)
    cv2.putText(img, str(crowed_num), (20, 50), 0, 1, (0, 255, 0), 2)
    print('检测到框内的人个数为：', crowed_num)
    if crowed_num < persons:
        return True
"""

class SecondRecordPosition:
    def __init__(self):
        self.boxes_position = []
        self.position = deque(maxlen=3)
        self.frame = 0

    def calculate_position(self):
        tag = 0
        if self.position:
            for p in self.position:
                # 判断当前帧中人框的坐标和上次记录中人框的距离差
                distance = [np.diff([p, b_p], axis=0) for b_p in self.boxes_position]
                # print('=-' * 8, distance)
                # 如果距离差出现小于20的情况，则说明是同一个人，上次记录保持不变，且删除box中的记录
                # dis_t = [[print('*'*6, a) for a in np.abs(dis[0]) if a < 20] for dis in distance]
                dis_j = [[1 for a in np.abs(dis[0]) if a < 20] for dis in distance]
                aa = [dis_j.index(dis) for dis in dis_j if sum(dis) > 2]
                if aa:
                    for a in aa:
                        self.boxes_position.pop(a)
                    pass
                # 如果距离差全大于20，则说明出现人员走动，打标签，等遍历完之后加到position中
                else:
                    tag += 1
            if tag > 0 and self.boxes_position:
                self.position.append(self.boxes_position[0])
        else:
            self.position.extend(self.boxes_position)
            self.boxes_position = []
        print(self.position)

    def show_person_box(self, box_info, img, camera_ip, alarm_num):
        y_len, x_len = img.shape[:2]
        person_num = 0
        self.frame += 1
        self.boxes_position = []
        for box, score, label in box_info:
            '''draw rectangles'''
            if label == 'person':
                y_min, x_min, y_max, x_max = box
                y_min, x_min, y_max, x_max = int(y_min * y_len), int(x_min * x_len), int(y_max * y_len), int(x_max * x_len)
                person_num += 1
                cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (0, 255, 0), thickness=3)
                if self.frame == 25:  # 每25帧判断一次
                    self.boxes_position.append([y_min, x_min, y_max, x_max])
                elif self.frame > 25:
                    self.frame = 0
        if self.boxes_position:
            self.calculate_position()

        if person_num < alarm_num:
            if self.boxes_position:
                print('0-'*8, self.boxes_position)
                point = self.boxes_position[0]
                cv2.rectangle(img, (point[1], point[0]), (point[3], point[2]), (0, 0, 255), thickness=3)
            #cv2.imshow(camera_ip, img)
            cv2.waitKey(1)
            return True
        else:
            # cv2.imshow(camera_ip, img)
            cv2.waitKey(1)
            return False

